import Vue from 'vue'
import Vuex from 'vuex'
import { getStore, setStore } from '@/util/mUtils'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    companyId: Number(getStore('companyId')) || 0,
    departmentId: Number(getStore('departmentId')) || 0,
    positionId: Number(getStore('positionId')) || 0,
    questionInput: getStore('questionInput') || '',
    invitedExperts: JSON.parse(getStore('invitedExperts') || '[]')
  },
  mutations: {
    SET_COMPANY(state, value) {
      state.companyId = value
    },
    SET_DEPARTMENT(state, value) {
      state.departmentId = value
    },
    SET_POSITION(state, value) {
      state.positionId = value
    },
    SET_QUESTION_INPUT(state, value) {
      state.questionInput = value
    },
    SET_INVITED_EXPERTS(state, list) {
      state.invitedExperts = list
    }
  },
  plugins: [
    (store) => {
      store.subscribe((mutation, state) => {
        switch (mutation.type) {
          case 'SET_COMPANY':
            setStore('companyId', state.companyId)
            break
          case 'SET_DEPARTMENT':
            setStore('departmentId', state.departmentId)
            break
          case 'SET_POSITION':
            setStore('positionId', state.positionId)
            break
          case 'SET_QUESTION_INPUT':
            setStore('questionInput', state.questionInput)
            break
          case 'SET_INVITED_EXPERTS':
            setStore('invitedExperts', JSON.stringify(state.invitedExperts))
            break
        }
      })
    }
  ]
})